package database;

//package au.com.bytecode.opencsv;

/**
Copyright 2005 Bytecode Pty Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * A very simple CSV writer released under a commercial-friendly license.
 *
 * @author Glen Smith
 * @author Tristan Daniel Boucher (Formatting)
 * @version Commit @24
 *
 */
public class CSVWriter implements Closeable 
{

  /**
   * The initial size of the written strings.
   */
  public static final int INITIAL_STRING_SIZE = 128;

  /** The character used for escaping quotes. */
  public static final char DEFAULT_ESCAPE_CHARACTER = '"';

  /** The default separator to use if none is supplied to the constructor. */
  public static final char DEFAULT_SEPARATOR = ',';

  /**
   * The default quote character to use if none is supplied to the
   * constructor.
   */
  public static final char DEFAULT_QUOTE_CHARACTER = '"';

  /** The quote constant to use when you wish to suppress all quoting. */
  public static final char NO_QUOTE_CHARACTER = '\u0000';

  /** The escape constant to use when you wish to suppress all escaping. */
  public static final char NO_ESCAPE_CHARACTER = '\u0000';

  /** Default line terminator uses platform encoding. */
  public static final String DEFAULT_LINE_END = "\n";

  /**
   * The basic writer object.
   */
  private Writer my_raw_writer;

  /**
   * The print writer object.
   */
  private PrintWriter my_pw;

  /**
   * The separator character.
   */
  private char my_separator;

  /**
   * The character used for quotations.
   */
  private char my_quote_char;

  /**
   * The escape character.
   */
  private char my_escape_char;

  /**
   * The character marking the end of a line.
   */
  private String my_line_end;

  /**
   * The result set helper object. 
   */
  private ResultSetHelper my_result_service = new ResultSetHelperService();

  /**
   * Constructs CSVWriter using a comma for the separator.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   */
  public CSVWriter(final Writer the_writer) 
  {
    this(the_writer, DEFAULT_SEPARATOR);
  }

  /**
   * Constructs CSVWriter with supplied separator.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   * @param the_separator
   *            the delimiter to use for separating entries.
   */
  public CSVWriter(final Writer the_writer, final char the_separator) 
  {
    this(the_writer, the_separator, DEFAULT_QUOTE_CHARACTER);
  }

  /**
   * Constructs CSVWriter with supplied separator and quote char.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   * @param the_separator
   *            the delimiter to use for separating entries
   * @param the_quotechar
   *            the character to use for quoted elements
   */
  public CSVWriter(final Writer the_writer, final char the_separator, 
                   final char the_quotechar) 
  {
    this(the_writer, the_separator, the_quotechar, DEFAULT_ESCAPE_CHARACTER);
  }

  /**
   * Constructs CSVWriter with supplied separator and quote char.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   * @param the_separator
   *            the delimiter to use for separating entries
   * @param the_quotechar
   *            the character to use for quoted elements
   * @param the_escapechar
   *            the character to use for escaping quotechars or escapechars
   */
  public CSVWriter(final Writer the_writer, final char the_separator, 
                   final char the_quotechar, final char the_escapechar) 
  {
    this(the_writer, the_separator, the_quotechar, the_escapechar, DEFAULT_LINE_END);
  }


  /**
   * Constructs CSVWriter with supplied separator and quote char.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   * @param the_separator
   *            the delimiter to use for separating entries
   * @param the_quotechar
   *            the character to use for quoted elements
   * @param the_line_end
   *        the line feed terminator to use
   */
  public CSVWriter(final Writer the_writer, final char the_separator, 
                   final char the_quotechar, final String the_line_end) 
  {
    this(the_writer, the_separator, the_quotechar, DEFAULT_ESCAPE_CHARACTER, the_line_end);
  }   



  /**
   * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
   *
   * @param the_writer
   *            the writer to an underlying CSV source.
   * @param the_separator
   *            the delimiter to use for separating entries
   * @param the_quotechar
   *            the character to use for quoted elements
   * @param the_escapechar
   *            the character to use for escaping quotechars or escapechars
   * @param the_line_end
   *        the line feed terminator to use
   */
  public CSVWriter(final Writer the_writer, final char the_separator, 
                   final char the_quotechar, final char the_escapechar, 
                   final String the_line_end) 
  {
    this.my_raw_writer = the_writer;
    this.my_pw = new PrintWriter(the_writer);
    this.my_separator = the_separator;
    this.my_quote_char = the_quotechar;
    this.my_escape_char = the_escapechar;
    this.my_line_end = the_line_end;
  }

  /**
   * Writes the entire list to a CSV file. The list is assumed to be a
   * String[]
   *
   * @param the_all_lines
   *            a List of String[], with each String[] representing a line of
   *            the file.
   */
  public void writeAll(final List<String[]> the_all_lines)  
  {
    for (String[] line : the_all_lines) 
    {
      writeNext(line);
    }
  }

  /**
   * Write result set as column names.
   * @param the_rs The result set.
   * @throws SQLException The exception thrown.
   */
  protected void writeColumnNames(final ResultSet the_rs)
    throws SQLException 
  {

    writeNext(my_result_service.getColumnNames(the_rs));
  }

  /**
   * Writes the entire ResultSet to a CSV file.
   *
   * The caller is responsible for closing the ResultSet.
   *
   * @param the_rs the recordset to write
   * @param the_include_column_names true if you want column names in the output, 
   * false otherwise.
   *
   * @throws java.io.IOException thrown by getColumnValue
   * @throws java.sql.SQLException thrown by getColumnValue
   */
  public void writeAll(final java.sql.ResultSet the_rs, 
                       final boolean the_include_column_names)  
    throws SQLException, IOException 
  {


    if (the_include_column_names) 
    {
      writeColumnNames(the_rs);
    }

    while (the_rs.next())
    {
      writeNext(my_result_service.getColumnValues(the_rs));
    }
  }


  /**
   * Writes the next line to the file.
   *
   * @param the_next_line
   *            a string array with each comma-separated element as a separate
   *            entry.
   */
  public void writeNext(final String[] the_next_line) 
  {

    if (the_next_line == null)
    {
      return;
    }

    final StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
    for (int i = 0; i < the_next_line.length; i++) 
    {

      if (i != 0) 
      {
        sb.append(my_separator);
      }

      final String next_element = the_next_line[i];
      if (next_element == null)
      {
        continue;
      }
      if (my_quote_char !=  NO_QUOTE_CHARACTER)
      {
        sb.append(my_quote_char);
      }

      sb.append(stringContainsSpecialCharacters(next_element) ? 
          processLine(next_element) : next_element);

      if (my_quote_char != NO_QUOTE_CHARACTER)
      {
        sb.append(my_quote_char);
      }
    }

    sb.append(my_line_end);
    my_pw.write(sb.toString());

  }

  /**
   * Returns true if the string contains special characters.
   * @param the_line The string in question.
   * @return There are special characters?
   */
  private boolean stringContainsSpecialCharacters(final String the_line) 
  {
    return the_line.indexOf(my_quote_char) != -1 || the_line.indexOf(my_escape_char) != -1;
  }

  /**
   * Overrideable method that determines how to process a line.
   * @param the_next_element The element to be processed.
   * @return The String builder that has the processed line.
   */
  protected StringBuilder processLine(final String the_next_element)
  {
    final StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
    for (int j = 0; j < the_next_element.length(); j++) 
    {
      final char nextChar = the_next_element.charAt(j);
      if (my_escape_char != NO_ESCAPE_CHARACTER && nextChar == my_quote_char) 
      {
        sb.append(my_escape_char).append(nextChar);
      } 
      else if (my_escape_char != NO_ESCAPE_CHARACTER && nextChar == my_escape_char) 
      {
        sb.append(my_escape_char).append(nextChar);
      } 
      else 
      {
        sb.append(nextChar);
      }
    }

    return sb;
  }

  /**
   * Flush underlying stream to writer.
   * 
   * @throws IOException if bad things happen
   */
  public void flush() throws IOException 
  {

    my_pw.flush();

  } 

  /**
   * Close the underlying stream writer flushing any buffered content.
   *
   * @throws IOException if bad things happen
   *
   */
  public void close() throws IOException 
  {
    flush();
    my_pw.close();
    my_raw_writer.close();
  }

  /**
   *  Checks to see if the there has been an error in the printstream. 
   *  
   *  @return Is there an error in the printwriter?
   */
  public boolean checkError() 
  {
    return my_pw.checkError();
  }

  /**
   * Setter for my_result_service.
   * @param the_result_service The result service passed.
   */
  public void setResultService(final ResultSetHelper the_result_service) 
  {
    this.my_result_service = the_result_service;
  }
}
//End of class CSVWriter
